;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; david functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defadvice kill-ring-save (before slickcopy activate compile)
  "When called interactively with no active region, copy a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
           (line-beginning-position 2)))))

(defadvice kill-region (before slickcut activate compile)
  "When called interactively with no active region, kill a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
           (line-beginning-position 2)))))

(defun david-publish-org (&optional arg)
  "Regexp place [^\\]_ with \_"
  (interactive "p")
  (replace-regexp "\\([^\\]\\)_" "\\1\\\\_" nil (point-min) (point-max))
  (call-interactively 'org-export-as-html))

(defun david-match-paren (arg)
  "Go to the matching paren if on a paren; otherwise insert %."
  (interactive "p")
  (let ((prev-char (char-to-string (preceding-char)))
        (next-char (char-to-string (following-char))))
    (cond ((string-match "[[{(<]" next-char) (forward-sexp 1))
          ((string-match "[\]})>]" prev-char) (backward-sexp 1))
          (t (self-insert-command (or arg 1))))))

(defun david-move-line (&optional n)
  "Move current line N (1) lines up/down leaving point in place."
  (interactive "p")
  (when (null n)
    (setq n 1))
  (let ((col (current-column)))
    (beginning-of-line)
    (next-line 1)
    (transpose-lines n)
    (previous-line 1)
    (forward-char col)))

(defun david-move-line-up (n)
  "Moves current line N (1) lines up leaving point in place."
  (interactive "p")
  (david-move-line (if (null n) -1 (- n)))) 

(defun david-move-line-down (n)
  "Moves current line N (1) lines down leaving point in place."
  (interactive "p")
  (david-move-line (if (null n) 1 n)))

(defun david-dump-line-down ()     
 "duplicate this line at next line"
 (interactive)
 (let ((c (current-column)))
   (beginning-of-line)
   (david-select-line-down)
   (beginning-of-line)
   (yank)
   (previous-line 1)
   (move-to-column c)))

(defun david-vi-open-next-line (arg)
  "Move to the next line (like vi) and then opens a line."
  (interactive "p")
  (end-of-line)
  (open-line arg)
  (next-line 1)
  (indent-according-to-mode))

(defun david-select-line-down ()
  "like Shift+down in UltraEdit."
  (interactive)
  (let ((s (point)))
    (setq next-line-add-newlines t)
    (next-line 1)
    (setq next-line-add-newlines nil)
    (kill-new (buffer-substring s (point)))))